package tiled.simple.gwt.client;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;

import tiled.simple.core.Map;

import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.event.dom.client.MouseMoveEvent;

public class Game {
	public static final float PIXEL_PER_METER=100;
 	
	private Map map;
	private MapRenderer mapRenderer=new MapRenderer();
	
	private World world;
	private JBox2DGWTTestbed testbed;
	private MapShapesProvider mapShapesProvider;
	private MapObjectsProvider mapObjectsProvider;
	
	
	public Game(Map map) {
		this.map=map;
		this.map.loadImages(mapRenderer);
		
		boolean doSleep = true;
		Vec2 gravity = new Vec2(2.0f, 10.0f);
		world = new World(gravity,doSleep);
		
		testbed = new JBox2DGWTTestbed(world);
		mapShapesProvider= new MapShapesProvider(world);
		mapObjectsProvider= new MapObjectsProvider(world);
		
		map.getObjectGroup("Collisions").loadShapes(mapShapesProvider);
		map.getObjectGroup("Entities").loadObjects(mapObjectsProvider);
		
		mapWidth=map.getWidth()*map.getTileWidth();
		mapHeight=map.getHeight()*map.getTileHeight();
	}
	
	private int canvasWidth=0;
	private int canvasHeight=0;

	private int mapWidth=0;
	private int mapHeight=0; 
		
	public void render(Context2d context,int refreshRate) {
		world.step((float)refreshRate/1000, 100, 100);
		
		mapRenderer.context=context;

		context.translate((canvasWidth-mapWidth)/2, (canvasHeight-mapHeight)/2);

		map.render(mapRenderer);
		mapObjectsProvider.render(context);
		testbed.render(context);

		context.translate(-(canvasWidth-mapWidth)/2, -(canvasHeight-mapHeight)/2);

    }
	
	public void resize(int canvasWidth, int canvasHeight) {
		this.canvasWidth=canvasWidth;
		this.canvasHeight=canvasHeight;
	}

	public void onMouseMove(MouseMoveEvent event) {
		Vec2 gravity=new Vec2(-(canvasWidth/2-event.getX()),-(canvasHeight/2-event.getY()));
		
		gravity.normalize();
		world.setGravity(gravity.mul(10f));
	}

}
